import type { MiddlewareHandler } from 'hono'
import { config } from '@/config/env'

// 简单的内存指标存储
const metrics = {
  requests: {
    total: 0,
    byMethod: new Map<string, number>(),
    byStatus: new Map<number, number>(),
    byPath: new Map<string, number>()
  },
  responseTime: {
    total: 0,
    count: 0,
    average: 0
  }
}

// 监控指标中间件
export const metricsMiddleware = (): MiddlewareHandler => {
  if (!config.monitoring.metricsEnabled) {
    return async (_, next) => {
      await next()
    }
  }

  return async (c, next) => {
    const start = Date.now()
    const method = c.req.method
    const path = c.req.path

    await next()

    const duration = Date.now() - start
    const status = c.res.status

    // 更新指标
    metrics.requests.total++
    metrics.requests.byMethod.set(method, (metrics.requests.byMethod.get(method) || 0) + 1)
    metrics.requests.byStatus.set(status, (metrics.requests.byStatus.get(status) || 0) + 1)
    metrics.requests.byPath.set(path, (metrics.requests.byPath.get(path) || 0) + 1)

    metrics.responseTime.total += duration
    metrics.responseTime.count++
    metrics.responseTime.average = metrics.responseTime.total / metrics.responseTime.count

    // 设置响应时间头
    c.header('X-Response-Time', `${duration}ms`)
  }
}

// 获取指标数据
export const getMetrics = () => {
  return {
    ...metrics,
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    memory: process.memoryUsage()
  }
}
